package leetcode.code2106;

import leetcode.IDebug;
import leetcode.helper.H;
import leetcode.templates.presum.MaxPreSums1;

public class Solution2 implements IDebug {

	public int maxTotalFruits(int[][] fruits, int startPos, int k) {
		int len = fruits.length;
		int[] poses = new int[len];
		int[] amounts = new int[len];
		for (int i = 0; i < len; i++) {
			poses[i] = fruits[i][0];
			amounts[i] = fruits[i][1];
		}
		long[] sums = this.presum(amounts);
		int L = Math.max(0, startPos - k), R = startPos + k;
		int posel = this.lbound(poses, L);
		int poser = this.rBound(poses, R);
		if (posel == -1 && poser == -1) {
			return 0;
		}
		long ans = 0;
		if (posel == -1) {
			return (int) this.sumIndex(sums, startPos, R);
		}
		ans = this.sumIndex(sums, posel, startPos);
		if (poser != -1) {
			ans = Math.max(this.sumIndex(sums, startPos, poser), ans);
		}
		for (int i = Math.max(posel, 0); poses[i] > startPos; i--) {

		}
		return (int) ans;
	}

	public int rBound(int[] arr, int target) {
		int ans = -1;
		int l = 0, r = arr.length - 1;
		while (l <= r) {
			int mid = l + ((r - l) >> 1);
			if (arr[mid] <= target) {
				ans = mid;
				l = mid + 1;
			} else {
				r = mid - 1;
			}
		}
		return ans;
	}

	public int lbound(int[] arr, int target) {
		int ans = -1;
		int l = 0, r = arr.length - 1;
		while (l <= r) {
			int mid = l + ((r - l) >> 1);
			if (arr[mid] >= target) {
				ans = mid;
				r = mid - 1;
			} else {
				l = mid + 1;
			}
		}
		return ans;
	}

	public long[] presum(int[] nums) {
		int len = nums.length;
		long[] sums = new long[len + 1];
		for (int i = 1; i < sums.length; i++) {
			sums[i] = sums[i - 1] + nums[i - 1];
		}
		return sums;
	}

	public long sumIndex(long[] sums, int indexL, int indexR) {
		return sums[indexR + 1] - sums[indexL];
	}

	@Override
	public void debug4() {
		H.compare(14, this.maxTotalFruits(H.str2array1("[[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]]"), 5, 4));
		H.compare(9, this.maxTotalFruits(H.str2array1("[[2,8],[6,3],[8,6]]"), 5, 4));
		H.compare(0, this.maxTotalFruits(H.str2array1("[[0,3],[6,4],[8,5]]"), 3, 2));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
